<?php 

namespace App\Http\Controllers;

use Exception;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Services\DedustingMiniService;
use App\Services\SmsService;
use App\Models\DedustingUser;
use App\Models\DedustingDevice;
use App\Models\DedustingLibrary;
use App\Models\DedustingRepair;
use App\Models\DedustingAlarmLog;
use App\Models\DedustingAlarm;
use App\Models\DedustingDevicePoint;
use App\Models\DedustingFeedback;
use App\Models\DedustingAdjustment;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class DedustingController extends Controller
{
    /**
     * [wxLogin 微信登陆]
     */
    public function wxLogin(Request $request)
    {

        if (!$request->has('code')) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '请传入 code']);
        }

        $param = $request->all();
        $code = $param['code'];

        try {
            $miniService = new DedustingMiniService();
            $result = $miniService->parseLoginCode($code);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }

        return response()->json(['code'=> 1, 'data' => $result, 'msg' => 'wxlogin success']);
    }

    /**
     * [sendVerifyCode 发送验证码]
     */
    public function sendVerifyCode(Request $request)
    {
        if (!$request->has('mobile')) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '请传入 mobile']);
        }

        $param = $request->all();
        $mobile = $param['mobile'];

        try {
            $sms = new SmsService();
            $res = $sms->sendVerifyCode($mobile);

            if ($res) {
                return response()->json(['code'=> 1, 'data' => '', 'msg' => '发送成功']);
            } else {
                return response()->json(['code'=> 0, 'data' => '', 'msg' => '发送失败']);
            }

        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getExceptions()]);
        }
    }

    /**
     * [register 注册]
     */
    public function register(Request $request)
    {
        $param = $request->all();

        if (!$request->has('mobile') || !$request->has('code')) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '请传入 手机号 或 验证码']);
        }

        $mobile = $param['mobile'];
        $code = $param['code'];

        //校验短信验证码
        $sms = new SmsService();
        $res = $sms->checkVerifyCode($mobile, $code);
        if (!$res) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '验证码错误']);
        }

        if (!$param['password'] || !$param['repassword'] || ($param['password'] != $param['repassword'])) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '两次密码不一致']);
        }

        try {

            //校验手机号是否存在
            $checkMobile =  DedustingUser::where('mobile', $mobile)->exists();
            if ($checkMobile) {
                return response()->json(['code'=> 0, 'data' => '', 'msg' => '该手机号已被注册']);
            }

            DB::beginTransaction();
            //校验设备码
            if ($request->has('device_code') && $request->device_code) {
                $checkDevice = DedustingDevice::where('code', $param['device_code'])->whereNull('bind_user_id')->exists();
                if (!$checkDevice) {
                    return response()->json(['code'=> 0, 'data' => '', 'msg' => '错误的设备码或设备已被绑定']);
                }

                $bindRes = DedustingDevice::userBind($param['device_code'], $param['user_id']);
                if (!$bindRes) {
                    DB::rollBack();
                    return response()->json(['code'=> 0, 'data' => '', 'msg' => '设备绑定失败']);
                }
            }

            $user = DedustingUser::findOrFail($param['user_id']);

            $user->mobile = $mobile;
            $user->password = Hash::make($param['password']);
            $user->nickname = isset($param['nickname']) ? $param['nickname'] : '';
            $user->duty = isset($param['duty']) ? $param['duty'] : '';
            
            if ($user->save()) {
                DB::commit();
                return response()->json(['code'=> 1, 'data' => $user, 'msg' => 'register success']);
            }
            DB::rollBack();
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    /**
     * [login 登陆]
     */
    public function login(Request $request)
    {
        if (!$request->has('mobile') || !$request->has('password')) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '请传入正确的手机号或密码']);
        }

        $param = $request->all();

        try {
            $userMobile =  DedustingUser::where('mobile', $param['mobile'])->firstOrFail();
            if (!Hash::check($param['password'], $userMobile->password)) {
                return response()->json(['code'=> 0, 'data' => '', 'msg' => '请传入正确的手机号或密码']);
            }

            return response()->json(['code'=> 1, 'data' => $userMobile, 'msg' => 'login success']);

        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '请传入正确的手机号或密码']);
        }
    }

    /**
     * [resetPassword 重置密码]
     */
    public function resetPassword(Request $request)
    {
        $param = $request->all();

        if (!$request->has('mobile') || !$request->has('code')) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '请传入 手机号 或 验证码']);
        }

        if (!$param['password'] || !$param['repassword'] || ($param['password'] != $param['repassword'])) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '两次密码不一致']);
        }

        $sms = new SmsService();
        $res = $sms->checkVerifyCode($param['mobile'], $param['code']);
        if (!$res) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '验证码错误']);
        }

        try {
            $userMobile =  DedustingUser::where('mobile', $param['mobile'])->firstOrFail();
            
            $userMobile->password = Hash::make($param['password']);

            if ($userMobile->save()) {
                return response()->json(['code'=> 1, 'data' => $userMobile, 'msg' => '修改成功']);
            }

        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '请传入正确的手机号或密码']);
        }
    }

    /**
     * [changePassword 修改密码]
     */
    public function changePassword(Request $request)
    {
        $param = $request->all();

        if (!$request->has('mobile') || empty($request->mobile)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '请传入正确的手机号']);
        }

        if (!$param['password'] || !$param['repassword'] || ($param['password'] != $param['repassword'])) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '两次密码不一致']);
        }

        try {
            $userMobile =  DedustingUser::where('mobile', $param['mobile'])->firstOrFail();
            
            if (!Hash::check($param['old_password'], $userMobile->password)) {
                return response()->json(['code'=> 0, 'data' => '', 'msg' => '原密码错误']);
            }

            $userMobile->password = Hash::make($param['password']);

            if ($userMobile->save()) {
                return response()->json(['code'=> 1, 'data' => $userMobile, 'msg' => '修改成功']);
            }

        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    /**
     * [changePassword 绑定设备]
     */
    public function bindDevice(Request $request)
    {
        if (!$request->has('user_id') || !$request->has('code')) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '错误的设备编码']);
        }

        $param = $request->all();

        try {
            $bindRes = DedustingDevice::userBind($param['code'], $param['user_id']);
            if ($bindRes) {
                return response()->json(['code'=> 1, 'data' => $bindRes, 'msg' => '绑定成功']);
            }
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '绑定失败，请检查设备码']);
        }

    }

    /**
     * [devices 设备列表]
     */
    public function devices(Request $request)
    {
        $param = $request->all();

        if (!$request->has('user_id') || empty($request->user_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '用户错误']);
        }

        $param = $request->all();
        $user = DedustingUser::findOrFail($request->user_id);
        if ($user['is_admin']) {
            $repairTotal = DedustingDevice::where('status', DedustingDevice::STATUS_REPAIR)
                ->count();

            $list = DedustingDevice::select(['id', 'name', 'maintain_at', 'location', 'status'])
            ->paginate($request->query('per_page', 15))
            ->toArray();
        } else {
            $repairTotal = DedustingDevice::where('bind_user_id', $param['user_id'])
                ->where('status', DedustingDevice::STATUS_REPAIR)
                ->count();

            $list = DedustingDevice::select(['id', 'name', 'maintain_at', 'location', 'status'])
            ->where('bind_user_id', $param['user_id'])
            ->paginate($request->query('per_page', 15))
            ->toArray();
        }

        $onlineTotal = 0;

        foreach ($list['data'] as &$one) {
            $redisDataKey = DedustingDevice::DATA_CACHE_KEY.$one['id'];
            $redisData = Redis::get($redisDataKey);
            $data = json_decode($redisData, true);

            if (in_array($one['status'], [DedustingDevice::STATUS_ONLINE, DedustingDevice::STATUS_OFFLINE])) {
                if (time() - $data['time'] > 60) {
                    $device['status'] = 2;
                } else {
                    $device['status'] = 1;
                    $onlineTotal++;
                }
            }
        }

        $list['repair_total'] = $repairTotal;
        $list['online_total'] = $onlineTotal;

        return response()->json(['code'=> 1, 'data' => $list, 'msg' => '查询成功']);
    }

    /**
     * [deviceInfo 设备信息]
     */
    public function deviceInfo(Request $request)
    {
        $param = $request->all();

        if (!$request->has('device_id') || empty($request->device_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '设备id错误']);
        }

        $param = $request->all();

        $fields = ['id', 'name', 'company', 'project', 'location', 'code', 'sell_at', 'maintenance', 'maintain_at'];

        try {
            $device = DedustingDevice::select($fields)->findOrFail($request->device_id);
            return response()->json(['code'=> 1, 'data' => $device, 'msg' => '查询成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    /**
     * [deviceData 设备信息]
     */
    public function deviceData(Request $request)
    {
        if (!$request->has('device_id') || empty($request->device_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '设备id错误']);
        }

        $param = $request->all();

        $fields = ['id', 'name', 'company', 'project', 'location', 'code', 'sell_at', 'maintain_at', 'status', 'total_alive', 'now_alive'];

        try {
            $device = DedustingDevice::select($fields)->findOrFail($request->device_id);
            
            $redisDataKey = DedustingDevice::DATA_CACHE_KEY.$device['id'];
            $redisData = Redis::get($redisDataKey);
            $data = json_decode($redisData, true);
            $data['mode'] = 1;
            $data['mode_text'] = DedustingDevicePoint::POINT_MODE[$data['mode']];

            $default = [];
            foreach (DedustingDevicePoint::POINTS as $key => $value) {
                $default[$key] = 0.00;
            }
            $data = array_merge($default, $data);

            $device['data'] = $data;
            $device['data_range'] = DedustingDevicePoint::ranges($device['id']);

            if (in_array($device['status'], [DedustingDevice::STATUS_ONLINE, DedustingDevice::STATUS_OFFLINE])) {
                if (empty($redisData) || (time() - $data['time'] > 60)) {
                    $device['status'] = 2;
                } else {
                    $device['status'] = 1;
                }
            }
            $device['status_text'] = DedustingDevice::STATUS_TEXT[$device['status']];

            $totalAliveDay = floor($device['total_alive'] / 86400);
            $totalAliveHour = floor(($device['total_alive'] - ($totalAliveDay * 86400)) / 3600);

            $nowAliveDay = floor($device['now_alive'] / 86400);
            $nowAliveHour = floor(($device['now_alive'] - ($nowAliveDay * 86400)) / 3600);

            $alive['total']['day'] = $totalAliveDay;
            $alive['total']['hour'] = $totalAliveHour;

            $alive['now']['day'] = $nowAliveDay;
            $alive['now']['hour'] = $nowAliveHour;

            $device['alive'] = $alive;
            return response()->json(['code'=> 1, 'data' => $device, 'msg' => '查询成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    public function deviceAdjustment(Request $request)
    {
        if (!$request->has('device_id') || empty($request->device_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '设备id错误']);
        }

        $param = $request->all();

        try {
            $data = DedustingAdjustment::where('device_id', $request->device_id)->firstOrFail();
            $data->detail = json_decode($data['detail'], true);

            return response()->json(['code'=> 1, 'data' => $data, 'msg' => '查询成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }        
    }

    /**
     * [libraries 文库列表]
     */
    public function libraries(Request $request)
    {
        $type1Total = DedustingLibrary::where('type', DedustingLibrary::TYPE_1)->count();
        $type2Total = DedustingLibrary::where('type', DedustingLibrary::TYPE_2)->count();
        $type3Total = DedustingLibrary::where('type', DedustingLibrary::TYPE_3)->count();

        $list = DedustingLibrary::select(['id', 'title', 'cover', 'question', 'views'])
            ->when(
                ($request->has('type') && !empty($request->type)), 
                function ($query) use ($request) {
                    return $query->where('type', $request->type);
                }
            )
            ->paginate($request->query('per_page', 15))
            ->toArray();

        $list['type_1_total'] = $type1Total;
        $list['type_2_total'] = $type2Total;
        $list['type_3_total'] = $type3Total;
        return response()->json(['code'=> 1, 'data' => $list, 'msg' => '查询成功']);
    }

    /**
     * [libraries 文库详情]
     */
    public function libraryDetail(Request $request)
    {
        $param = $request->all();

        if (!$request->has('library_id') || empty($request->library_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '文库id错误']);
        }

        $param = $request->all();

        $fields = ['id', 'title', 'question', 'question_img', 'question_video', 'judge', 'analyse', 'answer', 'answer_img', 'answer_video'];

        try {
            $library = DedustingLibrary::select($fields)->findOrFail($request->library_id);
            return response()->json(['code'=> 1, 'data' => $library, 'msg' => '查询成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    public function libraryView(Request $request)
    {
        $param = $request->all();

        if (!$request->has('library_id') || empty($request->library_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '文库id错误']);
        }

        $param = $request->all();

        try {
            $library = DedustingLibrary::findOrFail($request->library_id);
            $library->views++;
            $library->save();
            return response()->json(['code'=> 1, 'data' => '', 'msg' => '操作成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    /**
     * [repairs 维保记录]
     */
    public function repairs(Request $request)
    {
        if (!$request->has('device_id') || empty($request->device_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '设备id错误']);
        }

        $list = DedustingRepair::select(['id', 'detail', 'type', 'status', 'repair_at'])
            ->when(
                ($request->has('type') && !empty($request->type)), 
                function ($query) use ($request) {
                    return $query->where('type', $request->type);
                }
            )
            ->paginate($request->query('per_page', 15))
            ->toArray();
        
        foreach ($list['data'] as &$one) {
            $one['status_text'] = DedustingRepair::STATUS_TEXT[$one['status']];
        }

        return response()->json(['code'=> 1, 'data' => $list, 'msg' => '查询成功']);
    }

    /**
     * [alarms 报警列表]
     */
    public function alarms(Request $request)
    {
        if (!$request->has('user_id') || empty($request->user_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '用户id错误']);
        }

        $param = $request->all();

        try {
            $user = DedustingUser::findOrFail($request->user_id);
            if ($user['is_admin']) {
                $devices = DedustingDevice::pluck('id');
            } else {
                $devices = DedustingDevice::where('bind_user_id', $param['user_id'])->pluck('id');
            }

            $list = DedustingAlarmLog::select(['id', 'device_id', 'point', 'alarm_level', 'alarm_name', 'status', 'real_value', 'created_at', 'updated_at'])
            ->whereIn('device_id', $devices)
            ->when(
                $request->has('status'), 
                function ($query) use ($request) {
                    return $query->where('status', $request->status);
                }
            )
            ->when(
                $request->has('device_id'), 
                function ($query) use ($request) {
                    return $query->where('device_id', $request->device_id);
                }
            )
            ->with(['device:id,name'])
            ->paginate($request->query('per_page', 15))
            ->toArray();

            foreach ($list['data'] as &$one) {
                $one['unit'] = DedustingDevicePoint::POINT_UNITS[$one['point']];
                $one['level_text'] = DedustingAlarm::LEVEL_TEXT[$one['alarm_level']];
                $one['status_text'] = DedustingAlarmLog::STATUS_TEXT[$one['status']];
            }

            return response()->json(['code'=> 1, 'data' => $list, 'msg' => '查询成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    /**
     * [alarmDetail 报警详情]
     */
    public function alarmDetail(Request $request)
    {
        if (!$request->has('alarm_id') || empty($request->alarm_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '报警id错误']);
        }

        $param = $request->all();

        try {
            $detail = DedustingAlarmLog::select(['id', 'device_id', 'point', 'alarm_level', 'alarm_name', 'status', 'real_value', 'created_at', 'updated_at', 'library_id', 'operator'])
            ->with(['device:id,name'])
            ->with(['library:id,answer,answer_img,answer_video'])
            ->with(['admin:id,username'])
            ->findOrFail($param['alarm_id']);

            $detail->unit = DedustingDevicePoint::POINT_UNITS[$detail->point];
            $detail->level_text = DedustingAlarm::LEVEL_TEXT[$detail->alarm_level];
            $detail->status_text = DedustingAlarmLog::STATUS_TEXT[$detail->status];

            return response()->json(['code'=> 1, 'data' => $detail, 'msg' => '查询成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    public function dealAlarm(Request $request)
    {
        if (!$request->has('alarm_id') || empty($request->alarm_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '报警id错误']);
        }

        $param = $request->all();

        try {
            $detail = DedustingAlarmLog::findOrFail($param['alarm_id']);

            $detail->status = DedustingAlarmLog::STATUS_YES;

            $detail->save();

            return response()->json(['code'=> 1, 'data' => '', 'msg' => '修改成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    /**
     * [alarmCount 报警统计]
     */
    public function alarmCount(Request $request)
    {
        if (!$request->has('user_id') || empty($request->user_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '用户id错误']);
        }

        $param = $request->all();

        try {
            if (isset($param['device_id']) && !empty($param['device_id'])) {
                $devices = DedustingDevice::where('id', $param['device_id'])->pluck('id');
            } else {
                $user = DedustingUser::findOrFail($request->user_id);
                if ($user['is_admin']) {
                    $devices = DedustingDevice::pluck('id');
                } else {
                    $devices = DedustingDevice::where('bind_user_id', $param['user_id'])->pluck('id');
                }
            }

            $start = date("Y-m-d H:i:s", strtotime("-30 day"));
            $end = date("Y-m-d H:i:s");

            $countL1 = DedustingAlarmLog::whereIn('device_id', $devices)->where('alarm_level', DedustingAlarm::LEVEL_1)->whereBetween('created_at', [$start, $end])->count();
            $countL2 = DedustingAlarmLog::whereIn('device_id', $devices)->where('alarm_level', DedustingAlarm::LEVEL_2)->whereBetween('created_at', [$start, $end])->count();
            $countL3 = DedustingAlarmLog::whereIn('device_id', $devices)->where('alarm_level', DedustingAlarm::LEVEL_3)->whereBetween('created_at', [$start, $end])->count();

            // $countL1 = rand(10, 99);
            // $countL2 = rand(10, 99);
            // $countL3 = rand(10, 99);

            $total = $countL1 + $countL2 + $countL3;

            //柱状图
            $categories = [];
            $seriesData = [];
            $points = DedustingDevicePoint::POINTS;
            foreach ($points as $alias => $name) {
                $categories[] = $name;
                $seriesData[] = DedustingAlarmLog::whereIn('device_id', $devices)->where('point', $alias)->whereBetween('created_at', [$start, $end])->count();
                // $seriesData[] = rand(10, 99);
            }

            $columnChart['categories'] = $categories;
            $oneSeries = ['name' => '统计', 'data' => $seriesData];
            $columnChart['series'][] = $oneSeries;

            $categories = [];
            $seriesData = [];
            //折线图
            // $week = [
            //     'Monday' => '星期一', 
            //     'Tuesday' => '星期二',
            //     'Wednesday' => '星期三', 
            //     'Thursday' => '星期四', 
            //     'Friday' => '星期五', 
            //     'Sunday' => '星期六', 
            //     'Saturday' => '星期日'
            // ];

            $firstDay = date("Y-m-d", strtotime("-6 days"));
            for ($i=0; $i < 7; $i++) {
                $day = strtotime("$firstDay +$i days");
                $start = date("Y-m-d 00:00:00", $day);
                if ($i == 6) {  //today
                    $end = date("Y-m-d H:i:s");
                } else {
                    $end = date("Y-m-d 23:59:59", $day);
                }
                // $dayText = date('l', $day);
                // $categories[] = $week[$dayText];
                $categories[] = date("md", $day);
                $seriesData[] = DedustingAlarmLog::whereIn('device_id', $devices)->whereBetween('created_at', [$start, $end])->count();
                // $seriesData[] = rand(10, 99);
            }

            $lineChart['categories'] = $categories;
            $oneSeries = ['name' => '统计', 'data' => $seriesData];
            $lineChart['series'][] = $oneSeries;

            $data = [
                'total' => $total,
                'countL1' => $countL1,
                'countL2' => $countL2,
                'countL3' => $countL3,
                'column' => $columnChart,
                'line' => $lineChart
            ];

            return response()->json(['code'=> 1, 'data' => $data, 'msg' => '查询成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    public function feedback(Request $request)
    {
        if (!$request->has('user_id') || empty($request->user_id)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '用户id错误']);
        }

        if (!$request->has('detail') || empty($request->detail)) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => '请填写详情']);
        }

        $param = $request->all();
        try {
            //需要加敏感词检测 to do 
            $feedback = new DedustingFeedback();
            $feedback->user_id = $param['user_id'];
            $feedback->detail = $param['detail'];
            if (isset($param['images']) && $param['images']) {
                $feedback->image = json_encode($param['images'], JSON_UNESCAPED_SLASHES);
            }

            if (isset($param['videos']) && $param['videos']) {
                $feedback->video = json_encode($param['videos'], JSON_UNESCAPED_SLASHES);
            }

            $feedback->save();

            return response()->json(['code'=> 1, 'data' => '', 'msg' => '反馈成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }

    public function feedbackUpload(Request $request)
    {
        $param = $request->all();

        try {
            $name = md5(uniqid()). '.' .$param['file']->extension();
        
            $mimeType = $param['file']->getClientMimeType();
            $type = explode('/', $mimeType)[0];
            if ($type == 'image') {
                $path = $request->file('file')->storeAs(DedustingFeedback::IMAGE_PATH, $name, 'admin');
            } elseif ($type == 'video') {
                $path = $request->file('file')->storeAs(DedustingFeedback::VIDEO_PATH, $name, 'admin');
            }

            $url = env('APP_URL').'/uploads/'.$path;

            $data = [
                'fileType' => $type,
                'file' => $url
            ];

            return response()->json(['code'=> 1, 'data' => $data, 'msg' => '反馈成功']);
        } catch (Exception $e) {
            return response()->json(['code'=> 0, 'data' => '', 'msg' => $e->getMessage()]);
        }
    }
}